package com.oriole.api.module.sys.service.impl;

import com.oriole.api.module.sys.repository.SysRoleRepository;
import com.oriole.api.module.sys.service.ISysRoleService;
import com.oriole.entity.sys.QSysMenu;
import com.oriole.entity.sys.QSysRole;
import com.oriole.entity.sys.SysRole;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2020/10/11 23:16
 * Description:
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService {

    @Resource
    private SysRoleRepository sysRoleRepository;

    @Resource
    private JPAQueryFactory queryFactory;

    @Override
    public List<SysRole> findAll() {
        return sysRoleRepository.findAll();
    }

    @Override
    public SysRole findById(Long id) {
        return sysRoleRepository.findById(id).orElse(new SysRole());
    }

    @Override
    public Page<SysRole> findPage(Map<String, Object> condition, Pageable pageable) {
        if (null != condition && !condition.isEmpty()) {
            SysRole sysRole = new SysRole();
            if (condition.containsKey("name")) {
                sysRole.setName(condition.get("name").toString());
            }
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<SysRole> example = Example.of(sysRole, matcher);
            return sysRoleRepository.findAll(example, pageable);
        }
        return sysRoleRepository.findAll(pageable);
    }

    @Override
    public SysRole save(SysRole sysRole) {
        return sysRoleRepository.save(sysRole);
    }

    @Override
    public void deleteById(Long id) {
        sysRoleRepository.deleteById(id);
    }

    @Override
    public List<SysRole> findBySysUserId(Long sysUserId) {
        QSysRole sysRole = QSysRole.sysRole;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(sysRole.sysUsers.any().id.eq(sysUserId));
        return queryFactory.select(sysRole).from(sysRole).where(booleanBuilder).fetch();
    }
}
